package com.zzw.mis.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关过滤器

 * @author XiaoJie
 * @date 2025/06/03 10:21:10
 */
@Component
@Slf4j
public class GlobalAuthFilter implements GlobalFilter, Ordered {

	@Override
	public Mono<Void> filter (ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String path = request.getURI().getPath();
		if (StringUtils.isNotBlank(path)&&path.contains("/business/file/getDownload")) {
			// 构建新的请求头，替换 Content-Type
			HttpHeaders newHeaders = new HttpHeaders();
			newHeaders.putAll(request.getHeaders());
			newHeaders.setContentType(null); // 修改为目标 Content-Type
			// 构建新的请求
			ServerHttpRequest newRequest = request.mutate()
					.headers(HttpHeaders::clear)
					.headers(headers -> headers.putAll(newHeaders))
					.build();
			log.info("\n===>接受到请求\n" + "ip:{}\n" + "url:{}\n" + "method:{}\n"+ "ContentType:{}\n", newRequest.getRemoteAddress().getAddress().toString(), path, newRequest.getMethodValue(),newRequest.getHeaders().getContentType());
			return chain.filter(exchange.mutate().request(newRequest).build());
		}
		/*request.get*/
		log.info("\n===>接受到请求\n" + "ip:{}\n" + "url:{}\n" + "method:{}\n", request.getRemoteAddress().getAddress().toString(), path, request.getMethodValue());
		// //有token 校验token
		return chain.filter(exchange);

	}

	@Override
	public int getOrder () {
		return 0;
	}
}

